
class_name SceneDeploy
extends Node2D




var positions: Dictionary = {}
var current_unit: Unit = null
var current_area: Sprite2D = null




# 初始化
func _ready() -> void:
	for item in get_children():
		positions[ item.position ] = {
			"area": item,
			"unit": null
		}




func reset() -> void:
	current_unit = null
	if current_area:
		current_area.modulate = Color8(255, 255, 255)
		current_area = null




# 添加部署
func add_unit(_unit: Unit) -> void:
	# 遍历并找一个没有占用的位置给 unit
	for key in positions:
		if positions[key]["unit"] == null:
			positions[key]["unit"] = _unit
			add_child(_unit)
			_unit.position = key
			return




# 删除部署
func remove_unit(_unit: Unit) -> void:
	for key in positions:
		if positions[key]["unit"] == _unit:
			positions[key]["unit"] = null
			remove_child(_unit)
			_unit.position = Vector2.ZERO
			return




# 获取所有 unit
func get_units() -> Array[Unit]:
	var result: Array[Unit] = []
	for key in positions:
		if positions[key]["unit"] != null:
			result.push_back(positions[key]["unit"])
			remove_child(positions[key]["unit"])
			positions[key]["unit"] = null
	return result




# 交换部署位置
func adjust_unit(_unit: Unit) -> void:
	var swap: Vector2 = current_unit.position
	positions[ _unit.position ]["unit"] = current_unit
	current_unit.position = _unit.position
	positions[ swap ]["unit"] = _unit
	_unit.position = swap




# 指针调用
func pointer_callable(_pointer: ScenePointer) -> void:
	var pos: Vector2 = _pointer.position
	# 获取位置上的 unit
	if positions.has(pos):
		var unit: Unit = positions[ pos ]["unit"]
		# 判断 current_unit 是否为空
		# 不为空就调整他们的位置
		if current_unit != null:
			# 如果 unit 不为空就调用交换
			if unit != null:
				adjust_unit(unit)
			# 如果为 null 就直接交换
			else:
				positions[ current_unit.position ]["unit"] = null
				positions[ pos ]["unit"] = current_unit
				current_unit.position = pos
			
			current_unit = null
			current_area.modulate = Color8(255, 255, 255)
			current_area = null
		
		elif unit != null:
			current_unit = unit
			current_area = positions[ pos ]["area"]
			current_area.modulate = Color8(0, 255, 255)
